package com.engine.wei.base.ui.imageLoader;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Environment;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.bumptech.glide.GlideBuilder;
import com.bumptech.glide.annotation.GlideModule;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.cache.DiskLruCacheFactory;
import com.bumptech.glide.module.AppGlideModule;
import com.bumptech.glide.request.RequestOptions;
import com.engine.wei.base.utils.CacheManager;
import com.engine.wei.base.utils.log.LogUtils;

import java.io.File;

/**
 * 作者:赵若位
 * 时间:2020/9/28 15:39
 * 功能:
 */
@GlideModule
public class GlideUtils extends AppGlideModule {
    /*缓存目录的最大容量*/
    private static final long MAX_SIZE = 100 * 1024 * 1024;

    /*是否检测AndroidManifest里面的GlideModule*/
    @Override
    public boolean isManifestParsingEnabled() {
        return false;
    }

    @Override
    public void applyOptions(@NonNull Context context, @NonNull GlideBuilder builder) {
        super.applyOptions(context, builder);
        RequestOptions options = new RequestOptions();
        options.format(DecodeFormat.PREFER_RGB_565)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .centerCrop();

        File disk = CacheManager.getInstance().getPictureCacheFile();
        LogUtils.i("Glide硬盘缓存目录===>" + disk.getPath());
        builder.setDiskCache(new DiskLruCacheFactory(disk.getPath(), getDiskCacheSize()));
    }

    /*
     * 检测当前应用是否已经具有文件读取权限
     *
     * @param context
     * @return
     */
    private boolean isPermission(@Nullable Context context) {
        return ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) ==
                PackageManager.PERMISSION_GRANTED;
    }

    /*
     * 获取当前的缓存目录
     *
     * @param context
     * @return
     */
    private File getDiskCachePath(@Nullable Context context) {
        File file = null;
        if (isPermission(context) && Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), context.getPackageName());
            if (!file.exists()) {
                file.mkdirs();
            }
        } else {
            file = context.getExternalCacheDir();
        }
        return file;
    }

    /*
     * 硬盘缓存的最大容量
     *
     * @return 250m
     */
    private long getDiskCacheSize() {
        return MAX_SIZE;
    }
}
